//app.js
import Toast from './component/vant/toast/toast';
import Dialog from '/component/vant/dialog/dialog';

const {
    $Message
} = require('/component/iView/base/index');

App({
    onLaunch: function () {
        let _this = this

        //更新小程序
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
        })
        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        updateManager.onUpdateFailed(function () {
            // 新版本下载失败
        })
        // 登录
        let token = wx.getStorageSync('token')
        if (null != token && token != '') {
            //初始化用户信息
            _this.initUserData()
            //初始化用户菜单
            _this.getUserMenu()
            //更新用户微信信息
            _this.wxLogin()

            //监听蓝牙状态
            wx.onBLEConnectionStateChange(function (res) {
                // 该方法回调中可以用于处理连接意外断开等异常情况
                //如果连接的蓝牙deviceId不为空，则做校验
                if (_this.BLEInformation.deviceId && _this.BLEInformation.deviceId != '') {
                    if (res.deviceId == _this.BLEInformation.deviceId && !res.connected) {
                        _this.globalData.isConnBLE = false
                        wx.closeBLEConnection({
                            deviceId: _this.BLEInformation.deviceId,
                            success(res) {
                                console.log("断开蓝牙设备成功：" + res)
                            },
                            fail: function (res) {
                                console.log('断开蓝牙设备失败：' + res)
                            }
                        })
                    }
                }
                console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            })
        }
        this.globalData.sysinfo = wx.getSystemInfoSync()
        // 获取用户信息
        wx.getSetting({
            success: res => {
            }
        })
    },
    getModel: function () { //获取手机型号
        return wx.getSystemInfoSync()["model"]
    },
    getVersion: function () { //获取微信版本号
        return wx.getSystemInfoSync()["version"]
    },
    getSystem: function () { //获取操作系统版本
        return wx.getSystemInfoSync()["system"]
    },
    getPlatform: function () { //获取客户端平台
        return wx.getSystemInfoSync()["platform"]
    },
    getSDKVersion: function () { //获取客户端基础库版本
        return wx.getSystemInfoSync()["SDKVersion"]
    },
    globalData: {
        baseAPI: "http://127.0.0.1:8200",
        //用户信息
        userInfo: {},
        //品牌信息
        brandInfo: {},
        //常用设置信息
        setupInfo: {},
        pageSize: 10,
        templateIds: [],
        platform: "",
        screenWidth: wx.getSystemInfoSync().screenWidth,
        screenHeight: wx.getSystemInfoSync().screenHeight,
        // 是否连接蓝牙
        isConnBLE: false,
        //用户菜单列表
        menuList: [],
        //用户常用功能菜单
        commonMenuList: [],
        //当前页面的js
        currentPageJs: null
    },
    BLEInformation: {
        platform: "",
        deviceId: "",
        writeCharaterId: "",
        writeServiceId: "",
        notifyCharaterId: "",
        notifyServiceId: "",
        readCharaterId: "",
        readServiceId: "",
    },
    message: function (content, type) {
        let duration = 2
        if (type != 'success') {
            duration = 3
        }
        $Message({
            content: content,
            type: type,
            duration: duration
        });
    },
    toast: function (content, type) {
        Toast({
            type: type,
            message: content
        })
    },
    formPost: function (url, data) {
        let _this = this
        return new Promise(function (resolve, reject) {
            wx.showNavigationBarLoading();
            wx.request({
                url: _this.globalData.baseAPI + url,
                header: {
                    'content-type': 'application/json',
                    'Authorization': wx.getStorageSync('token')
                },
                method: 'POST',
                data,
                success(res) {
                    if (res.statusCode !== 200 || typeof res.data !== 'object') {
                        reject('网络出错')
                        return false;
                    }
                    if (res.data.code === 0) {
                        resolve(res.data);
                        return true;
                    } else if (res.data.code === 9999) {
                        console.log("跳转登录界面")
                        Dialog.confirm({
                            title: '登录提醒',
                            message: '未登录，是否去登录',
                        })
                            .then(() => {
                                console.log("confirm")
                                // on confirm
                                wx.navigateTo({
                                    url: "/pages/login/index"
                                })
                            })
                            .catch(() => {
                                console.log("concel")
                                // on cancel
                            });

                        return false;
                    } else {
                        resolve(res.data)
                        return false;
                    }
                },
                fail(res) {
                    reject(res.errMsg)
                    return false;
                },
                complete(res) {
                    wx.hideNavigationBarLoading();
                }
            })
        })
    },
    formGet: function (url, data) {
        let _this = this
        return new Promise(function (resolve, reject) {
            wx.showNavigationBarLoading();
            wx.request({
                url: _this.globalData.baseAPI + url,
                header: {
                    'Authorization': wx.getStorageSync('token')
                },
                method: 'GET',
                data,
                success(res) {
                    if (res.statusCode !== 200 || typeof res.data !== 'object') {
                        reject('网络出错')
                        return false;
                    }
                    if (res.data.code === 0) {
                        resolve(res.data);
                        return true;
                    } else if (res.data.code === 9999) {
                        console.log("跳转登录界面")
                        Dialog.confirm({
                            title: '登录提醒',
                            message: '未登录，是否去登录',
                        })
                            .then(() => {
                                console.log("confirm")
                                // on confirm
                                wx.navigateTo({
                                    url: "/pages/login/index"
                                })
                            })
                            .catch(() => {
                                console.log("concel")
                                // on cancel
                            });

                        return false;
                    } else {
                        console.log("reject")
                        // _this.toast(res.data.message, "fail")
                        // _this.message(res.data.message, "error")
                        resolve(res.data)
                        return false;
                    }
                },
                fail(res) {
                    reject(res.errMsg)
                    return false;
                },
                complete(res) {
                    wx.hideNavigationBarLoading();
                }
            })
        })
    },
    //微信授权登录
    wxLogin: function () {
        let _this = this
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                if (res.code) {
                    let url = '/app/wx/login?code=' + res.code
                    _this.formPost(url, null).then(res => {
                        if (res.code == 0) {
                            console.log("微信授权登录success")
                        } else {
                            wx.showToast({
                                title: '登录失败',
                                icon: 'none',
                                duration: 2000
                            })
                            console.log("微信授权登录fail, %o", res)
                        }
                    }).catch(e => {
                        wx.showToast({
                            title: '登录异常',
                            icon: 'none',
                            duration: 2000
                        })
                    })
                } else {
                    wx.showToast({
                        title: '获取code失败',
                        icon: 'none',
                        duration: 2000
                    })
                }
            }
        })
    },
    initUserData: function () {
        let _this = this
        let data = {}
        data.osType = _this.getModel()
        data.osVersion = _this.getSystem()
        _this.formGet('/app/boss/info', data).then(res => {
            if (res.code == 0) {
                let userInfo = res.data.userInfo
                let printer = res.data.printer
                let brand = res.data.brand
                let setup = res.data.setup
                // 用户信息
                if (userInfo != null) {
                    _this.globalData.userInfo = userInfo
                }
                // 打印机信息
                if (printer != null) {
                    _this.BLEInformation.platform = printer.osType
                    _this.BLEInformation.deviceId = printer.deviceId
                    _this.BLEInformation.writeCharaterId = printer.writeCharaterId
                    _this.BLEInformation.writeServiceId = printer.writeServiceId
                    _this.BLEInformation.notifyCharaterId = printer.notifyCharaterId
                    _this.BLEInformation.notifyServiceId = printer.notifyServiceId
                    _this.BLEInformation.readCharaterId = printer.readCharaterId
                    _this.BLEInformation.readServiceId = printer.readServiceId
                    console.log("设置打印机信息成功")
                }
                // 品牌信息
                if (brand != null) {
                    _this.globalData.brandInfo = brand
                }
                // 常用设置
                if (setup != null) {
                    _this.globalData.setupInfo = setup
                }

                //如果用户已过期，则跳转到升级页面
                if (userInfo == null || userInfo.isExpired == true) {
                    Dialog.confirm({
                        title: '会员已过期',
                        message: '是否去续费会员？',
                    })
                        .then(() => {
                            wx.navigateTo({
                                url: "/pages/usercenter/paymember/buy/index"
                            })
                        })
                        .catch(() => {
                            console.log("concel")
                            // on cancel
                        });
                }
            } else {
                console.log("用户数据初始化失败，%o" + res)
            }
        })
    },
    getUserMenu: function () {
        let _this = this
        _this.formGet('/app/boss/role/menu', null).then(res => {
            if (res.code == 0) {
                _this.globalData.menuList = res.data.list
            } else {
                console.log("获取用户菜单失败，%o" + res)
            }
        })
    }
})
